<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'thumbnail',
        'video_url',
        'duration',
        'views',
        'likes',
        'category_id',
        'user_id',
        'is_featured',
        'is_active'
    ];

    protected $casts = [
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
        'views' => 'integer',
        'likes' => 'integer'
    ];

    // 关联分类
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 关联评论
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    // 获取缩略图URL
    public function getThumbnailUrlAttribute()
    {
        if ($this->thumbnail) {
            // 如果图片路径已经是完整URL，直接返回
            if (str_starts_with($this->thumbnail, 'http')) {
                return $this->thumbnail;
            }
            // 如果图片路径以/开头，直接返回
            if (str_starts_with($this->thumbnail, '/')) {
                return $this->thumbnail;
            }
            // 否则作为相对路径处理
            return '/' . ltrim($this->thumbnail, '/');
        }
        return '/images/videos/default.jpg';
    }

    // 获取视频URL
    public function getVideoUrlAttribute($value)
    {
        if (!$value) {
            return null;
        }
        
        // 如果已经是完整URL，直接返回
        if (str_starts_with($value, 'http')) {
            return $value;
        }
        
        // 如果是相对路径，直接返回
        if (str_starts_with($value, '/')) {
            return $value;
        }
        
        // 否则作为storage路径处理
        return asset('storage/' . $value);
    }
}
